import 'package:lz_app_core/constants/app_manager.dart';
import 'package:lz_app_core/extension/kd_empty_extension.dart';
import 'package:lz_app_core/extension/kd_string_extension.dart';
import 'package:lz_app_core/kd_user/kd_user_info.dart';
import 'package:lz_app_core/utils/kd_storage.dart';
import 'package:lz_app_core/utils/log_utils.dart';
import 'package:lz_app_core/utils/sp_util.dart';
import 'package:lz_login/src/serve/models/kd_go_page.dart';
import 'package:lz_login/src/serve/models/kd_mine_certification_info_model.dart';
import 'package:lz_login/src/serve/models/kd_mine_info_detail_model.dart';
import 'package:lz_login/src/serve/models/lz_mine_corp_info_model.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:lz_rx_tool/kd_rx_tool.dart';
import 'package:lz_ui/kd_ui.dart';
import 'dart:io';
import '../bean/user_login_rsp_entity.dart';

enum KDLoginUrl {
  sendLoginMsgCode('lanzhi-app-customer/appSendLoginSms'),
  login('lanzhi-app-customer/appAccountLogin'),

  /// app登录后跳转到什么页面
  getGoPage('lanzhi-app-customer/getGoPage'),

  /// 获取货主企业id，根据会员id，目前只在货主端使用
  getCorpinfo('lanzhi-crm-info/queryCustomerCorpByMemberId'),

  /// 我的信息详情
  mineInfo('lanzhi-app-customer/getMemberDetail'),

  /// 忘记密码发送验证码逻辑
  sendForgotPwdVerification("lanzhi-main/sendForgotPwdVerification"),

  /// 忘记密码点击确认第一步
  forgotPwdFirst("lanzhi-main/forgotPwdFirst"),

  /// 忘记密码点击确认提交
  forgotPwdSave("lanzhi-main/forgotPwdSave"),

  /// 注册
  sendRegisterMsgCode('lanzhi-main/sendRegistrationVerification'),
  register('lanzhi-main/generalRegistration'),

  miniConfirmRole('lanzhi-app-customer/appConfirmRole'),

  /// 修改密码
  appUpdatePassword('lanzhi-app-customer/appUpdatePassword'),

  /// 修改手机-老手机号码发送验证码
  appUpdatePhoneByAppSendSms('lanzhi-app-customer/appUpdatePhoneByAppSendSms'),

  /// app修改手机号-老手机号码 验证码校验
  appUpdatePhoneByCheckAuthCode(
      'lanzhi-app-customer/appUpdatePhoneByCheckAuthCode'),

  /// app修改手机号新手机号发送短信验证码
  appUpdateNewPhoneSendSms('lanzhi-app-customer/appUpdateNewPhoneSendSms'),

  /// app修改手机号-新手机验证
  appUpdatePhone('lanzhi-app-customer/appUpdatePhone'),

  /// 获取当前app本版信息 （版本升级控制）
  getAppVersionDetailByPackageType(
      'lanzhi-app-customer/getAppVersionDetailByPackageType'),

  /// 推送app存储别名
  appSaveDriverAlias("lanzhi-bcs-message/appSaveDriverAlias"),

  /// 推送app删除
  appClearDriverAliasTwo("lanzhi-bcs-message/appClearDriverAliasTwo"),
  ;

  final String url;
  const KDLoginUrl(this.url);
}

class KDLoginApi {
  /// 登录
  /// 登录-发手机验证码
  static Future<bool> sendLoginMsgCode(String phone) async {
    KDRxResponse res = await KDRxHttp.post(KDLoginUrl.sendLoginMsgCode.url,
        showHud: true,
        params: {
          "account": phone,
          'loginType': 2,
          "applicationCode": AppManager.appName.appCode,
          'applicationName': AppManager.appName.applicationName,
        });

    return res.success;
  }

  /// 验证码登录
  static Future<bool> codeLogin(
      {required String phone, required String code}) async {
    KDRxResponse res = await KDRxHttp.post(KDLoginUrl.login.url,
        showHud: true,
        modelBuilder: KDUserInfo.fromJson,
        params: {
          'account': phone,
          'loginType': 2,
          'applicationCode': AppManager.appName.appCode,
          'applicationName': AppManager.appName.applicationName,
          'password': code
        });
    if (res.success) {
      KDStorage.save(KDStorageKey.phone.name, phone);
      KDUser.save(userJson: res.dataJson!["data"], userInfo: res.data!);
    }
    return res.success;
  }

  /// 密码登录
  static Future<bool> login(
      {required String phone, required String pwd}) async {
    String? asPwd;
    if (pwd == "" || pwd == null) {
      asPwd = null;
    } else {
      asPwd = KDString.aESEnCode(pwd);
    }

    KDRxResponse<KDUserInfo> res =
        await KDRxHttp.post<KDUserInfo>(KDLoginUrl.login.url,
            showHud: true,
            params: {
              'account': phone,
              'loginType': 1,
              'applicationCode': AppManager.appName.appCode,
              'applicationName': AppManager.appName.applicationName,
              'password': asPwd
            },
            modelBuilder: KDUserInfo.fromJson);
    if (res.success) {
      /// 登陆成功记住手机号码
      KDStorage.save(KDStorageKey.phone.name, phone);
      KDStorage.save(KDStorageKey.pwd.name, pwd);

      UserLoginRspEntity userLoginRspEntity =
          UserLoginRspEntity.fromJson(res.dataJson!);

      String? memberId = "";
      String? memberCertificationNumber = "";

      /// 空判断
      if (!KDIsEmpty.listEmpty(
          userLoginRspEntity.data?.userMainOrgAndMemberVOS)) {
        memberId = userLoginRspEntity.data?.userMainOrgAndMemberVOS
            ?.elementAt(0)
            .memberId;
      }

      if (!KDIsEmpty.listEmpty(
          userLoginRspEntity.data?.userMainOrgAndMemberVOS)) {
        memberCertificationNumber = userLoginRspEntity
            .data?.userMainOrgAndMemberVOS
            ?.elementAt(0)
            .memberCertificationNumber;
      }

      SpUtils.setString('memberId', memberId ?? '');
      SpUtils.setString(
          'memberCertificationNumber', memberCertificationNumber ?? '');
      

      KDUser.save(userJson: res.dataJson!["data"], userInfo: res.data!);
    }

    return res.success;
  }

  /// 注册
  /// 注册-发手机验证码
  static Future<bool> sendRegisterMsgCode(String phone) async {
    KDRxResponse res = await KDRxHttp.post(KDLoginUrl.sendRegisterMsgCode.url,
        params: {"registrationAccount": phone, "registrationMethod": 1},
        showHud: true);

    return res.success;
  }

  /// 注册
  static Future<bool> register(
      {required String phone,
      required String code,
      required String pwd}) async {
    String asPwd = KDString.aESEnCode(pwd);
    KDRxResponse res = await KDRxHttp.post(KDLoginUrl.register.url,
        params: {
          "registrationAccount": phone,
          "registrationCaptcha": code,
          'registrationMethod': 1,
          'registrationPassword': asPwd
        },
        showHud: true);

    return res.success;
  }

  /// 忘记密码
  /// 发送验证吗
  static Future<bool> sendForgotPwdVerification(String phone) async {
    KDRxResponse res = await KDRxHttp.get(
        KDLoginUrl.sendForgotPwdVerification.url,
        showHud: true,
        params: {"phone": phone});
    return res.success;
  }

  /// 忘记密码点击确认第一步
  /// phone phone
  /// captcha 验证吗
  static Future<bool> forgotPwdFirst({
    required String phone,
    required String captcha,
  }) async {
    KDRxResponse res = await KDRxHttp.get(
      KDLoginUrl.forgotPwdFirst.url,
      showHud: true,
      params: {"phone": phone, "captcha": captcha},
    );
    return res.success;
  }

  /// 忘记密码点击确认提交
  static Future<bool> forgotPwdSave({
    required String phone,
    required String captcha,
    required password,
  }) async {
    /// 密码加密
    String asPwd = KDString.aESEnCode(password);
    KDRxResponse res = await KDRxHttp.post(
      KDLoginUrl.forgotPwdSave.url,
      showHud: true,
      params: {
        "phone": phone,
        "captcha": captcha,
        "password": asPwd,
        "confirmPassword": asPwd,
      },
    );
    return res.success;
  }

  /// app登录后跳转到什么页面
  /// 1-未订购角色，2-有未提交认证，到认证页面，3-到首页
  static Future<KDGoPage?> getGoPage() async {
    KDRxResponse res = await KDRxHttp.get<KDGoPage>(KDLoginUrl.getGoPage.url,
        modelBuilder: KDGoPage.fromJson);
    return res.data;
  }

  /// 货主的企业信息，目前只在货主端使用
  static Future<bool> getCorpInfo() async {
    KDRxResponse<LZCorpInfoDetailModel> res = await KDRxHttp.post<
        LZCorpInfoDetailModel>(KDLoginUrl.getCorpinfo.url,
        params: {'memberId':KDUser.info.orgMemberId},
        showHud: true, modelBuilder: LZCorpInfoDetailModel.fromJson);
    if (res.success) {
      KDStorage.save(KDStorageKey.corpId.name, res.data?.corpId ?? '' );
    }
    return res.success;
  }

  /// 我的信息详情
  static Future<KDInfoDetailModel?> mineDetailInfo() async {
    var res = await KDRxHttp.get<KDInfoDetailModel>(KDLoginUrl.mineInfo.url,
        showHud: true, modelBuilder: KDInfoDetailModel.fromJson);
    return res.data;
  }

  /// 我的信息列表
  static Future<List<KDMineCertificationInfoModel>?> mineInfo() async {
    var res = await KDRxHttp.get<KDMineCertificationInfoModel>(
        KDLoginUrl.mineInfo.url,
        key: "data.memberAuthInfoVOList",
        showHud: true,
        modelBuilder: KDMineCertificationInfoModel.fromJson);
    return res.list;
  }

  static miniConfirmRole() async {
    var res = await KDRxHttp.post(KDLoginUrl.miniConfirmRole.url, params: {
      "isSignedRoleAgreement": "1",
      "applicationCode": AppManager.appName.appCode,
      'applicationName': AppManager.appName.applicationName,
    });
    if (res.success) {
      return res.dataJson?["data"];
    }
  }

  /// 修改密码
  static Future<bool> appUpdatePassword({
    required String oldPassword,
    required password,
  }) async {
    KDRxResponse res = await KDRxHttp.post(
      KDLoginUrl.appUpdatePassword.url,
      showHud: true,
      params: {
        "newPassword": KDString.aESEnCode(password),
        "oldPassword": KDString.aESEnCode(oldPassword)
      },
    );
    return res.success;
  }

  /// 修改手机-老手机号码发送验证码
  static Future<bool> appUpdatePhoneByAppSendSms({
    required String phone,
  }) async {
    KDRxResponse res = await KDRxHttp.get(
      KDLoginUrl.appUpdatePhoneByAppSendSms.url,
      showHud: true,
      params: {
        "phone": phone,
      },
    );
    return res.success;
  }

  /// app修改手机号-老手机号码 验证码校验
  static Future<bool> appUpdatePhoneByCheckAuthCode({
    required String phone,
    required String authCode,
  }) async {
    KDRxResponse res = await KDRxHttp.post(
      KDLoginUrl.appUpdatePhoneByCheckAuthCode.url,
      showHud: true,
      params: {
        "phone": phone,
        "authCode": authCode,
      },
    );
    return res.success;
  }

  /// app修改手机号新手机号发送短信验证码
  static Future<bool> appUpdateNewPhoneSendSms({
    required String phone,
  }) async {
    KDRxResponse res = await KDRxHttp.get(
      KDLoginUrl.appUpdateNewPhoneSendSms.url,
      showHud: true,
      params: {
        "phone": phone,
      },
    );
    return res.success;
  }

  /// app修改手机号-新手机验证
  static Future<bool> appUpdatePhone({
    required String phone,
    required String authCode,
  }) async {
    KDRxResponse res = await KDRxHttp.post(
      KDLoginUrl.appUpdatePhone.url,
      showHud: true,
      params: {
        "phone": phone,
        "authCode": authCode,
      },
    );
    return res.success;
  }

  /// # 推送
  /// 推送app存储别名

  static Future<bool> appSaveDriverAlias() async {
    var jpushId = KDStorage.getForKey(KDStorageKey.jpushId);
    if (jpushId == null) return false;
    var res = await KDRxHttp.post(
      KDLoginUrl.appSaveDriverAlias.url,
      showHud: false,
      showErrorToast: false,
      params: {
        "appAlias": "${AppManager.appName.appCode}_${KDUser.info.phone}",
        "registrationId": jpushId,
        "systemType": AppManager.appName.systemType,
      },
    );
    return res.success;
  }

  /// 推送app删除
  static Future<bool> appClearDriverAliasTwo() async {
    var jpushId = KDStorage.getForKey(KDStorageKey.jpushId);
    if (jpushId == null) return false;
    var res = await KDRxHttp.get(
      KDLoginUrl.appClearDriverAliasTwo.url,
      showHud: false,
      showErrorToast: false,
      params: {
        "appAlias": "${AppManager.appName.appCode}_${KDUser.info.phone}",
        "registrationId": jpushId,
        "systemType": AppManager.appName.systemType,
      },
    );
    return res.success;
  }
}
